package com.example.demo.util;

import cn.hutool.json.JSONUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.example.demo.entity.TUser;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 何景航
 * @date 2025/3/11 15:54
 */
public class JWTUtil {
    public static final String secret = "0S/12dSd0=;2Sfdjkgh3OPYs ";

    public static void main(String[] args) {
        TUser tUser = new TUser();
        tUser.setId(10282);
        tUser.setLoginAct("cat");
        tUser.setEmail("cat@163.com");
        String userJson = JSONUtil.toJsonStr(tUser);
        String token = createToken(userJson);
        System.out.println(token);
        System.out.println(verify(token));
        System.out.println(parseToken(token));
    }
    public static String createToken(String userJson) {
        Map<String, Object> header = new HashMap<>();
        header.put("alg", "HS256");
        header.put("typ", "JWT");
        return JWT.create()
                .withHeader(header)
                .withClaim("user", userJson)
                .withClaim("phone", "13725121212")
                .withClaim("email", "13725121212@139.com")
                .sign(Algorithm.HMAC256(secret));
    }
    public static Boolean verify(String token) {
        try {
            JWT.require(Algorithm.HMAC256(secret)).build().verify(token);
            return true;
        }catch (Exception e){
            e.printStackTrace();
        }
        return false;
    }
    public static String parseToken(String token) {
        try{
            JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(secret)).build();
//            DecodedJWT decodedJWT = jwtVerifier.verify(token);
//            Claim user = decodedJWT.getClaim("user");
//            return user.asString();
            return jwtVerifier.verify(token).getClaim("user").asString();
        }catch (Exception e){
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        }

}






















